package com.changjiang.luban.admin;

import com.changjiang.luban.config.annotation.CurrentUser;
import com.changjiang.luban.dao.domain.sys.SysUser;
import com.changjiang.luban.service.sys.SysUserServiceI;
import com.changjiang.luban.utils.data.Tree;
import com.changjiang.luban.utils.http.CookieUtils;
import com.changjiang.luban.utils.http.TokenUtils;
import com.changjiang.luban.utils.result.ApiResult;
import com.changjiang.luban.utils.result.ApiResultCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * IndexController
 * Description:
 *
 * @author nichangjiang@vip.qq.com
 * @version v0.1
 * @date 2018/6/9 - 17:31
 */
@SuppressWarnings("ALL")
@Controller
public class IndexController {

    @Autowired
    private SysUserServiceI sysUserServiceI;

    /**
     * 访问登录模板
     * @return 模板地址
     */
    @GetMapping("/login")
    public String login(){
        return "/login";
    }

    @PostMapping("/login")
    public String login(String userName, String passWord, HttpServletRequest request, HttpServletResponse response){
        SysUser user = sysUserServiceI.login(userName, passWord);
        if(user!=null){
            String token = TokenUtils.createJwtToken(user.getUserName());
            CookieUtils.setCookieToken(response,token);
            request.getSession().setAttribute("user",user);
            return "redirect:/";
        }
        request.getSession().setAttribute("resultMsg", ApiResult.failure(ApiResultCode.USER_LOGIN_ERROR));
        return "redirect:/login";
    }


    /**
     * 访问登录模板
     * @return 模板地址
     */
    @GetMapping("/")
    public String index(){
        return "/index";
    }


    @RequestMapping("/menu")
    @ResponseBody
    public ApiResult menu(@CurrentUser SysUser user){
        List<Tree> treeList = sysUserServiceI.tree(user.getId());
        if(treeList!=null){
            return ApiResult.success(treeList);
        }
        return ApiResult.failure(ApiResultCode.DATA_NONE);
    }

}
